package com.car.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.commons.core.model.Result;
import com.car.commons.core.model.WoniuException;
import com.car.commons.web.util.StateUtil;
import com.car.order.annotation.StockLogAnnotation;
import com.car.order.client.CarAccountClient;
import com.car.order.client.CarServeClient;
import com.car.order.client.model.clerk.ClerkDto;
import com.car.order.client.model.serve.serveProject.ServeProjectDto;
import com.car.order.dto.stock.StockDto;
import com.car.order.entity.form.stock.StockFindListForm;
import com.car.order.entity.form.stock.StockFindPageForm;
import com.car.order.entity.form.stock.StockUpdateForm;
import com.car.order.entity.param.stock.StockInsertParam;
import com.car.order.entity.param.stock.StockUpdateParam;
import com.car.order.mapper.StockMapper;
import com.car.order.entity.Stock;
import com.car.order.service.StockService;
import com.car.order.util.PageDtoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 杜岷芫
 * @since 2024-08-29 11:43:37
 */
@Service
@Slf4j
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    @Autowired
    private StockMapper stockMapper;
    @Resource
    private CarAccountClient carAccountClient;
    @Resource
    private CarServeClient carServeClient;

    @Override
    public Page<StockDto> findPage(StockFindPageForm form) {
        HashSet<Integer> set = new HashSet<>();
        set.add(form.getClerkId());
        System.out.println("*&^"+set);
        Result<ClerkDto> clerkById = carAccountClient.findClerkById(form.getClerkId());
        if (clerkById.getCode() != 200) {
            throw new WoniuException(clerkById.getCode(), clerkById.getMsg());
        }
        Page<Stock> page = new Page<>(form.getPageNum()==null?1:form.getPageNum(),form.getPageSize()==null?6:form.getPageSize());
        QueryWrapper<Stock> query = new QueryWrapper<>();
        query.eq("store_id", form.getClerkId());
        if (ObjectUtil.isNotEmpty(form.getName())) {
            query.like("serve_project_name", form.getName());
        }
        Page<Stock> stockPage = stockMapper.selectPage(page, query);
        Page<StockDto> stockDtoPage = PageDtoUtil.convertPage(stockPage, StockDto.class);
        Set<Integer> adminIds = stockDtoPage.getRecords().stream().map(StockDto::getAdminId).collect(Collectors.toSet());
        Set<Integer> serveProjectIds = stockDtoPage.getRecords().stream().map(StockDto::getServeProjectId).collect(Collectors.toSet());
        List<StockDto> records = stockDtoPage.getRecords();
        HashMap<Integer, ClerkDto> clerkDtoHashMap = new HashMap<>();
        if (adminIds.size() != 0) {
            Result<List<ClerkDto>> clerksResult = carAccountClient.findsClerksByIds(adminIds);
            if (clerksResult.getCode() != 200) {
                throw new WoniuException(clerksResult.getCode(), clerksResult.getMsg());
            }
            List<ClerkDto> clerkDtos = clerksResult.getData();
            if (clerkDtos == null || clerkDtos.size() != adminIds.size()) {
                throw new WoniuException(500, "有门店管理员没查到");
            }
            for (ClerkDto clerkDto : clerkDtos) {
                clerkDtoHashMap.put(clerkDto.getClerkId(), clerkDto);
            }

        }
        HashMap<Integer, ServeProjectDto> projectDtoHashMap = new HashMap<>();
        if (serveProjectIds.size() != 0) {
            Result<List<ServeProjectDto>> serveProjectResult= carServeClient.findServeProjectListByIds(serveProjectIds);
            if (serveProjectResult.getCode() != 200) {
                throw new WoniuException(serveProjectResult.getCode(), serveProjectResult.getMsg());
            }
            List<ServeProjectDto> serveProjectDtos = serveProjectResult.getData();
            if (serveProjectDtos == null || serveProjectDtos.size() != serveProjectIds.size()) {
                throw new WoniuException(500, "有服务项目没有查到");
            }

            for (ServeProjectDto serveProjectDto : serveProjectDtos) {
                projectDtoHashMap.put(serveProjectDto.getProjectId(), serveProjectDto);
            }
            for (StockDto record : records) {
            }
        }
        for (StockDto record : records) {
            ClerkDto clerkDto = clerkDtoHashMap.get(record.getAdminId());
            record.setAdminName(clerkDto==null?"用户":clerkDto.getClerkName());
            ServeProjectDto serveProjectDto = projectDtoHashMap.get(record.getServeProjectId());
            record.setServeProjectName(serveProjectDto==null?"服务项目":serveProjectDto.getProjectName());
        }
        stockDtoPage.setRecords(records);
        return stockDtoPage;
    }

    @Override
    public List<Stock> findList(StockFindListForm form){
        QueryWrapper<Stock> query = new QueryWrapper<>();
        return stockMapper.selectList(query);
    }

    @Override
    public Stock findById(Integer id) {
        return stockMapper.selectById(id);
    }

    @Override
    @StockLogAnnotation(desc = StateUtil.Stock_TYPE_INSERT)
    public Stock insert(StockInsertParam param) {
        Result<List<Integer>> result = carAccountClient.getAllStoresId();
        if (result.getCode() != 200) {
            throw new WoniuException(result.getCode(), result.getMsg());
        }
        List<Integer> storesIds = result.getData();
        System.out.println(storesIds);
        ArrayList<Stock> stocks = new ArrayList<>();
        Stock stock = BeanUtil.toBean(param, Stock.class);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        stock.setModifyTime(LocalDateTime.now().format(formatter));
        for (Integer storesId : storesIds) {
            stock.setStoreId(storesId);
            stock.setStock(100);
            stocks.add(stock);
        }
        System.out.println(stocks);
        boolean save = saveBatch(stocks);
        if (!save) {
            throw new WoniuException(500, "新增失败");
        }
        return stock;
    }

    @Override
    public Stock update(StockUpdateForm form) {
        Stock stock = BeanUtil.toBean(form, Stock.class);
        boolean b = updateById(stock);
        if (!b) {
            throw new WoniuException(500, "修改失败");
        }
        return stock;
    }

    @Override
    public void changeState(Integer id, Integer state) {
        Stock stock = stockMapper.selectById(id);
        if (ObjectUtil.isEmpty(stock)) {
            throw new WoniuException(500, "库存不存在");
        }
        if (stock.getState().equals(state)) {
            throw new WoniuException(500, "该库存状态异常");
        }
        stock.setState(state);
        int i=stockMapper.updateById(stock);
        if (i == 0) {
            throw new WoniuException(500, "修改状态失败");
        }
    }

    @Override
    public Stock clerkIdInsert(StockInsertParam param) {
        Stock stock = BeanUtil.toBean(param, Stock.class);
        stock.setAdminId(param.getClerkId());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        stock.setModifyTime(LocalDateTime.now().format(formatter));
        int insert = stockMapper.insert(stock);
        if (insert == 0) {
            throw new WoniuException(500, "新增库存失败");
        }
        return stock;
    }

    @Override
    @StockLogAnnotation(desc = StateUtil.Stock_TYPE_ADD)
    public Stock add(StockUpdateParam param) {
        Stock stock = stockMapper.selectById(param.getId());
        if (ObjectUtil.isEmpty(stock)) {
            throw new WoniuException(500, "该库存不存在");
        }
        if (!stock.getState().equals(StateUtil.STOCK_STATE_NOMAL)) {
            throw new WoniuException(500, "该库存状态异常");
        }
        stock.setStock(stock.getStock() + param.getStock());
        stock.setAdminId(param.getAdminId());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        stock.setModifyTime(LocalDateTime.now().format(formatter));
        int i = stockMapper.updateById(stock);
        if (i == 0) {
            throw new WoniuException(500, "增加库存量失败");
        }
        return stock;
    }

    @Override
    @StockLogAnnotation(desc = StateUtil.Stock_TYPE_REDUCE)
    public Stock reduce(StockUpdateParam param) {
        Stock stock = stockMapper.selectById(param.getId());
        if (ObjectUtil.isEmpty(stock)) {
            throw new WoniuException(500, "该库存不存在");
        }
        if (!stock.getState().equals(StateUtil.STOCK_STATE_NOMAL)) {
            throw new WoniuException(500, "该库存状态异常");
        }
        if (stock.getStock() < param.getStock()) {
            throw new WoniuException(500, "库存量不足");
        }
        stock.setStock(stock.getStock() - param.getStock());
        stock.setAdminId(param.getAdminId());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        stock.setModifyTime(LocalDateTime.now().format(formatter));
        int i = stockMapper.updateById(stock);
        if (i == 0) {
            throw new WoniuException(500, "减少库存量失败");
        }
        return stock;
    }

    @Override
    @StockLogAnnotation(desc = StateUtil.Stock_TYPE_ChANGE)
    public Stock changeStock(StockUpdateParam param) {
        Result<ClerkDto> clerkById = carAccountClient.findClerkById(param.getAdminId());
        if (clerkById.getCode() != 200) {
            throw new WoniuException(clerkById.getCode(), clerkById.getMsg());
        }
        ClerkDto clerkDto = clerkById.getData();
        if (clerkDto == null) {
            throw new WoniuException(500, "门店管理员不存在");
        }

        Stock stock = stockMapper.selectById(param.getId());
        if (ObjectUtil.isEmpty(stock)) {
            throw new WoniuException(500, "该库存不存在");
        }
        if (!stock.getState().equals(StateUtil.STOCK_STATE_NOMAL)) {
            throw new WoniuException(500, "该库存状态异常");
        }
        if (!stock.getStoreId().equals(clerkDto.getStoresId())) {
            throw new WoniuException(500, "不能修改其他门店的库存");
        }
        stock.setStock(param.getStock());
        stock.setAdminId(param.getAdminId());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        stock.setModifyTime(LocalDateTime.now().format(formatter));
        int i = stockMapper.updateById(stock);
        if (i == 0) {
            throw new WoniuException(500, "修改库存量失败");
        }
        return stock;
    }

}